package com.etoak.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.enums.ResultEnum;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.web.properties.ImageProperties;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    ImageProperties imageProperties;

    @PostMapping("/image")
    public ResultVO<String> upload(MultipartFile image) throws IOException {
        if(ObjectUtils.isEmpty(image) || image.isEmpty()){
            return ResultVO.failed(ResultEnum.FILE_NULL_ERROR);
        }

        String contentType = image.getContentType();
        if(!imageProperties.getTypes().contains(contentType)){
            String message = imageProperties.getTypes().stream().map(x ->
                    x.substring(x.lastIndexOf("/")+1)).collect(Collectors.joining("、"));
            return ResultVO.failed(ResultEnum.SYSTEM_ERROR.getCode(),"仅支持"+message);
        }

        String originalFilename = image.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        String filename = IdUtil.simpleUUID() + StrUtil.DOT + suffix;
        File uploadDir = new File(imageProperties.getLocation());
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }

        File desFile = new File(uploadDir,filename);
        image.transferTo(desFile);
        String path = imageProperties.getPrefix().endsWith("/") ? imageProperties.getPrefix() + filename : imageProperties.getPrefix() + "/" + filename;
        return ResultVO.success(path);
    }
}
